﻿using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using JiveMessenger.Common;
using JiveMessenger.Converters;
using JiveMessenger.Models;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using JiveMessenger.ViewModels;
using JmShared;
using Newtonsoft.Json;
using NotificationsExtensions.TileContent;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace JiveMessenger.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : BasicPage, INotifyPropertyChanged
    {
        private bool _firstPivotSwipe = true;
        private bool _ifLoadState = true;
        private bool _ifSaveState = false;
        private bool _isRotating;
        private bool _isInputPanelOpen;
        private int _landscapeYTransformDistance = 54;
        //private Canvas _pinAndTrashContainer;
        //private Image _pinTabImage;
        //private Image _removeTabImage;
        //private bool _crossedPinThreshold;
        //private bool _crossedDeleteThreshold;
        //private bool _deleteFlickOccured;
        //private bool _pinFlickOccured;
        //private static double FLICK_VELOCITY = 1.5;
        //private NavigationHelper navigationHelper;
        private Dictionary<ApplicationViewOrientation, double> _keyboardHeights;



        //public double VisibleBoundsHeight
        //{
        //    get { return (double)GetValue(VisibleBoundsHeightProperty); }
        //    set { SetValue(VisibleBoundsHeightProperty, value); }
        //}

        //// Using a DependencyProperty as the backing store for VisibleBoundsHeight.  This enables animation, styling, binding, etc...
        //public static readonly DependencyProperty VisibleBoundsHeightProperty =
        //    DependencyProperty.Register("VisibleBoundsHeight", typeof(double), typeof(MainPage), new PropertyMetadata(0));


        private double _visibleBoundsHeight;
        public double VisibleBoundsHeight
        {
            get { return _visibleBoundsHeight; }
            set
            {
                if (_visibleBoundsHeight != value)
                {
                    _visibleBoundsHeight = value;
                    RaisePropertyChanged("VisibleBoundsHeight");
                }
            }
        }

        private double _visibleBoundsWidth;
        public double VisibleBoundsWidth
        {
            get { return _visibleBoundsWidth; }
            set
            {
                if (_visibleBoundsWidth != value)
                {
                    _visibleBoundsWidth = value;
                    RaisePropertyChanged("VisibleBoundsWidth");
                }
            }
        }

        public MainPage()
        {
           
            this.InitializeComponent();
            ViewModelMainPage vm = this.DataContext as ViewModelMainPage;
            ViewModelLocator locator = App.Current.Resources["Locator"] as ViewModelLocator;
            var pmStatusConverter = this.Resources["PmStatusConverter"] as PmStatusConverter;
            pmStatusConverter.ViewModelMainPage = this.DataContext as ViewModelMainPage;

            _keyboardHeights = new Dictionary<ApplicationViewOrientation, double>();
            _keyboardHeights[ApplicationViewOrientation.Landscape] = 219;// 273;
            _keyboardHeights[ApplicationViewOrientation.Portrait] = 340;

            this.NavigationCacheMode = NavigationCacheMode.Required;
            ApplicationView.GetForCurrentView().VisibleBoundsChanged += MainPage_VisibleBoundsChanged;
            Application.Current.Resuming += App_Resuming;
            Application.Current.Suspending += App_Suspending;

            Windows.UI.ViewManagement.InputPane.GetForCurrentView().Showing += InputPanel_Showing;
            Windows.UI.ViewManagement.InputPane.GetForCurrentView().Hiding += InputPanel_Hiding;
            StatusBar statusBar = StatusBar.GetForCurrentView();
            statusBar.ForegroundColor = Colors.White;

            this.DataContextPlaceholder.DataContext = this;

            var root = Window.Current.Content as Frame;
            root.RenderTransform = new CompositeTransform() { TranslateY = 0 };

            vm.DeviceOrientation = ApplicationView.GetForCurrentView().Orientation;

            Task.Run(async () =>
            {
                await DispatcherHelper.RunAsync(async () =>
                {
                    vm.TabButtonImageUri = await CreateTabButtonImage(vm.ChatViewModels.Count).ConfigureAwait(false);
                });
            });
            RegisterMessengers();

            if (StaticMethods.GetIsInternetAvailable())
                locator.CurrentClient.StartConnectTask(true);
        }



        private void RegisterMessengers()
        {


            Messenger.Default.Register<NotificationMessage>(this, msg =>
            {
                switch (msg.Notification)
                {
                    //case "OpenOptions":
                    //    Frame.Navigate(typeof(SettingsPage));
                    //    break;
                    case "ShowFakeKeyboardAnimation":
                        ShowFakeKeyboardAnimation(true);
                        break;
                    case "RemoveFakeKeyboardAnimation":
                        RemoveFakeKeyboardAnimation();
                        break;
                    case "HideContactList":
                        this.ContactList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        this.ContactList.Opacity = 0;
                        break;
                    case "ShowContactList":
                        this.ContactList.Visibility = Windows.UI.Xaml.Visibility.Visible;
                        this.ContactList.Animate(0, 1, "Opacity", 300, 0);
                        break;
                    case "LockMainPagePivot":
                        this.JivePivot.IsLocked = true;
                        break;
                    case "UnlockMainPagePivot":
                        this.JivePivot.IsLocked = false;
                        break;
                    case "ShowProgressbar":
                        this.ProgressBar.IsIndeterminate = true;
                        this.ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
                        break;
                    case "HideProgressbar":
                        this.ProgressBar.IsIndeterminate = false;
                        this.ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        break;

                }
            });

            Messenger.Default.Register<NotificationMessageAction<Uri>>(this, async msg =>
            {
                switch (msg.Notification)
                {
                    case "CreateTabButtonImage":
                        {
                            await DispatcherHelper.RunAsync(async () =>
                            {
                                var result = await CreateTabButtonImage(Convert.ToInt32(msg.Target));
                                msg.Execute(result);

                            });

                            break;
                        }
                }
            });

            Messenger.Default.Register<NotificationMessage<double>>(this, msg =>
            {
                switch (msg.Notification)
                {
                    case "SetStatusBarValue":
                        this.ProgressBar.IsIndeterminate = false;
                        this.ProgressBar.Value = msg.Content;
                        break;
                }
            });

         
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _ifSaveState = e.NavigationMode == NavigationMode.Forward;
            base.OnNavigatedFrom(e);
            ((ViewModelMainPage)this.DataContext).ShowEmoticonPopup = false;
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ViewModelLocator locator = (ViewModelLocator)Application.Current.Resources["Locator"];
            //  _ifLoadState = e.NavigationMode == NavigationMode.New;
            base.OnNavigatedTo(e);
            // TODO: Prepare page for display here.

            this.ChatControlsContentControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (!_ifLoadState)
                this.ContactList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.EmoticonPopup.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.MainPageConnectPopup.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.TabsPopup.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.TextBlockGroupNameTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.ChatControlsContentControl.Opacity = 0;
            this.ContactList.Opacity = 0;
            this.BnNotifications.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            this.EmoticonPopup.IsOpen = true;
            await Task.Delay(100);
            this.ChatControlsContentControl.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.ChatControlsContentControl.Animate(0, 1, "Opacity", 100, 0);
            await Task.Delay(100);
            if (!_ifLoadState)
                this.ContactList.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.ContactList.Animate(0, 1, "Opacity", 100, 200);
            await Task.Delay(50);
            this.EmoticonPopup.Visibility = Windows.UI.Xaml.Visibility.Visible;
            await Task.Delay(50);
            this.MainPageConnectPopup.Visibility = Windows.UI.Xaml.Visibility.Visible;
            await Task.Delay(50);
            this.TabsPopup.Visibility = Windows.UI.Xaml.Visibility.Visible;
            await Task.Delay(50);
            this.TextBlockGroupNameTop.Visibility = Windows.UI.Xaml.Visibility.Visible;
            if (locator.ViewModelNotifications.Notifications.Count > 0)
                this.BnNotifications.Visibility = Windows.UI.Xaml.Visibility.Visible;
            // await Task.Delay(500);
            StatusBar.GetForCurrentView().ShowAsync();
        }

        protected override void SaveState(SaveStateEventArgs e)
        {
            base.SaveState(e);
            if (e.PageState == null)
                return;
            if (!_ifSaveState)
                return;

            ViewModelLocator locator = (ViewModelLocator)Application.Current.Resources["Locator"];
            ViewModelMainPage vm = this.DataContext as ViewModelMainPage;
            if (vm.ChatViewModels.Count > 0)
            {
                e.PageState["ChatViewModels"] = vm.ChatViewModels;
                List<IContact> contactsToStore = new List<IContact>();
                IContact currentUser = locator.ViewModelContactList.CurrentUser;

                foreach (ViewModelChat chatVm in vm.ChatViewModels)
                {
                    var chatContacts = new List<IContact>();
                    //if (chatVm is ViewModelPrivateMessage)
                    //{
                    //    var contact = ((ViewModelPrivateMessage)chatVm).PmTarget;
                    //    if (!chatContacts.Contains(contact))
                    //        chatContacts.Add(contact);
                    //}
                    //else if (chatVm is ViewModelGroupChat)
                    //{
                    //    IChatGroup group = currentUser.ChatGroups.FirstOrDefault(x => x.ID == ((ViewModelGroupChat)chatVm).ID);

                    var groupContacts = locator.ViewModelContactList.Contacts.Where(x => chatVm.Messages.Any(msg => msg.Sender.Equals(x)));
                    foreach (IContact contact in groupContacts)
                    {
                        if (!chatContacts.Contains(contact))
                            chatContacts.Add(contact);
                    }
                    //}

                    foreach (IContact cont in chatContacts)
                    {
                        var contact = cont.Clone();
                        List<JiveCustomEmoticonModel> customEmoticons = new List<JiveCustomEmoticonModel>();
                        foreach (MessageModel model in chatVm.Messages.Where(x => x.Sender.Equals(contact)))
                        {
                            var emoticonMatches = model.MessageItems.Where(msgItem => msgItem.MatchType == MessageTextObjectMatchType.CustomEmoticon);
                            foreach (MessageTextObjectMatch match in emoticonMatches)
                            {
                                JiveCustomEmoticonModel emoticonModel = contact.CustomEmoticons.FirstOrDefault(x => x.EmoticonShortcut == match.MatchWord);
                                if (!customEmoticons.Contains(emoticonModel))
                                    customEmoticons.Add(emoticonModel);
                            }
                        }
                        contact.CustomEmoticons = new ObservableCollection<JiveCustomEmoticonModel>(customEmoticons);
                        if (!contactsToStore.Contains(contact))
                            contactsToStore.Add(contact);
                        else
                        {
                            foreach (var emoticonModel in customEmoticons)
                            {
                                var existingContact = contactsToStore.FirstOrDefault(x => x.Equals(contact));
                                if (!existingContact.CustomEmoticons.Contains(emoticonModel))
                                    existingContact.CustomEmoticons.Add(emoticonModel);
                            }
                        }
                    }
                }
                if (!contactsToStore.Contains(currentUser))
                    contactsToStore.Add(currentUser);
                e.PageState["Contacts"] = new ObservableCollection<IContact>(contactsToStore);// VmHelper.Locator.ViewModelContactList.Contacts;

                if (vm.CurrentActiveViewModel != null)
                    e.PageState["CurrentActiveViewModel"] = vm.CurrentActiveViewModel.ID;
            }

            if (locator.CurrentClient.IsLoggedIn)
            {
                e.PageState["CurrentUserID"] = locator.CurrentClient.CurrentUserInfo.UserID;
            }



            e.PageState["MainPivotIndex"] = vm.SelectedPivotItemIndex;
        }

        protected override void LoadState(LoadStateEventArgs e)
        {
            base.LoadState(e);
            if (e.PageState == null)
            {
                return;
            }
            if (e.PageState.Count == 0)
                return;

            if (!_ifLoadState)
                return;
            //Task.Run(async () =>
            //    {

            ViewModelLocator locator = null;


            locator = App.Current.Resources["Locator"] as ViewModelLocator;

            ObservableCollection<IContact> contacts = e.PageState["Contacts"] as ObservableCollection<IContact>;
            locator.ViewModelContactList.Contacts = contacts;
            //   Messenger.Default.Send(new NotificationMessage(this, ViewModelContactList.MessengerCommands.CreateVisualGroups.ToString()));
            object currentUserID = "";
            if (e.PageState.TryGetValue("CurrentUserID", out currentUserID))
            {
                locator.ViewModelContactList.CurrentUser = contacts.FirstOrDefault(x => x.UserID == (string)currentUserID);
            }


            ObservableCollection<ViewModelTab> tabs = e.PageState["ChatViewModels"] as ObservableCollection<ViewModelTab>;



            foreach (ViewModelChat chat in tabs.Where(x => x is ViewModelChat))
            {
                foreach (MessageModel msg in chat.Messages)
                {
                    IContact contact = null;

                    Messenger.Default.Send(new NotificationMessageAction<IContact>(this, msg.SenderID, "GetContactFromUserID", cont =>
                    {
                        contact = cont;
                    }));

                    msg.Sender = contact;
                    msg.RefreshMessageItems();
                }
            }
            object activeVmID = "";
            e.PageState.TryGetValue("CurrentActiveViewModel", out activeVmID);

            ViewModelMainPage vm = this.DataContext as ViewModelMainPage;
            vm.ChatViewModels = tabs;
            if (vm.ChatViewModels.Count > 0 && !string.IsNullOrEmpty(activeVmID as string))
            {
                var selectedVm = vm.ChatViewModels.FirstOrDefault(x => x.ID == activeVmID as string);
                if (selectedVm != null)
                    vm.CurrentActiveViewModel = selectedVm;
            }
            vm.SelectedPivotItemIndex = (int)e.PageState["MainPivotIndex"];


            IClient client = VmHelper.Locator.CurrentClient;
            if (!client.IsLoggedIn && StaticMethods.GetIsInternetAvailable())
                client.StartConnectTask(true);
            _ifLoadState = false;

        }


        private async Task<Uri> CreateTabButtonImage(int count)
        {
            if (count <= 3)
            {
                return new Uri(string.Format("ms-appx:///Assets/AppBar/tabs/tab{0}.png", count));
            }
            string fileName = string.Format("tab{0}.png", count);
            StorageFolder folder = await StaticMethods.GetTabImageStorageFolder();


            bool exists = StaticMethods.FileExistsSync(fileName, folder);

            if (!exists)
            {
                StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);

                var renderTargetBitmap = new RenderTargetBitmap();


                Capture_Grid.Visibility = Windows.UI.Xaml.Visibility.Visible;
                Capture_Grid.Opacity = 1;
                await renderTargetBitmap.RenderAsync(Capture_Grid);
                var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

                int height = renderTargetBitmap.PixelHeight;
                int width = renderTargetBitmap.PixelWidth;
                int offset;
                byte[] pixelArray = pixelBuffer.ToArray();
                for (int row = 0; row < (uint)height; row++)
                {
                    for (int col = 0; col < (uint)width; col++)
                    {
                        offset = (row * (int)width * 4) + (col * 4);
                        byte red = pixelArray[offset];       // Red
                        byte green = pixelArray[offset + 1]; // Green
                        byte blue = pixelArray[offset + 2];  // Blue
                        byte alpha = pixelArray[offset + 3]; // Alpha

                        //Alpha of 255 means fully non-transparent. 0 means transparent.
                        if (alpha > 200)
                        {
                            //red,green and blue at 0 means black, 255 means white
                            if (red < 200 && green < 200 && blue < 200)
                            {
                                //Set pixel to transparent
                                pixelArray[offset + 3] = 0;
                            }
                        }
                    }
                }

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
                    await DispatcherHelper.RunAsync(() =>
                         {
                             encoder.SetPixelData(
                                 BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Straight,
                                 (uint)renderTargetBitmap.PixelWidth,
                                 (uint)renderTargetBitmap.PixelHeight, 96d, 96d,
                                 pixelArray);
                         });
                    await encoder.FlushAsync();

                }
                Capture_Grid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                Capture_Grid.Opacity = 0;
            }
            return new Uri(string.Format("ms-appdata:///Local/{0}/{1}", StaticSettings.TabImageFolder, fileName), UriKind.Absolute);
        }

        private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {

            ViewModelMainPage mainPageVm = (ViewModelMainPage)this.DataContext;
            ViewModelChat currentActiveVm = mainPageVm.CurrentActiveViewModel as ViewModelChat;
            if (currentActiveVm != null)
            {
                currentActiveVm.IsInputTextFocused = false;
                mainPageVm.ShowFauxKeyboardGrid = false;
                mainPageVm.ShowEmoticonPopup = false;
            }
            _ifLoadState = true;
        }
        private void App_Resuming(object sender, object e)
        {

        }


        void InputPanel_Showing(Windows.UI.ViewManagement.InputPane sender, Windows.UI.ViewManagement.InputPaneVisibilityEventArgs args)
        {

            args.EnsuredFocusedElementInView = true;

            if (_isInputPanelOpen)
                return;
            ViewModelMainPage mainPageVm = this.DataContext as ViewModelMainPage;

            var chatVm = mainPageVm.CurrentActiveViewModel as ViewModelChat;
            if (chatVm == null)
                return;

            if (args.OccludedRect.Height > 0)
            {
                mainPageVm.EmoticonControlHeight = mainPageVm.FauxKeyboardHeight = args.OccludedRect.Height;
                if (mainPageVm.DeviceOrientation == ApplicationViewOrientation.Landscape)
                {
                    mainPageVm.FauxKeyboardHeight -= _landscapeYTransformDistance;

                }
                _keyboardHeights[mainPageVm.DeviceOrientation] = mainPageVm.FauxKeyboardHeight;
                Debug.WriteLine("keyboard height:" + mainPageVm.FauxKeyboardHeight);
            }
            mainPageVm.ShowFauxKeyboardGrid = true;

            _isInputPanelOpen = true;
        }

        void InputPanel_Hiding(Windows.UI.ViewManagement.InputPane sender, Windows.UI.ViewManagement.InputPaneVisibilityEventArgs args)
        {
            ViewModelMainPage mainPageVm = this.DataContext as ViewModelMainPage;
            ViewModelChat chatVm = (ViewModelChat)mainPageVm.CurrentActiveViewModel;
            if (chatVm != null)
            {
                if (!mainPageVm.ShowEmoticonPopup)
                    mainPageVm.ShowFauxKeyboardGrid = false;
            }
            _isInputPanelOpen = false;
        }
        async void MainPage_VisibleBoundsChanged(ApplicationView sender, object args)
        {
            ViewModelMainPage mainPageVm = (ViewModelMainPage)this.DataContext;
            ViewModelChat currentActiveVm = mainPageVm.CurrentActiveViewModel as ViewModelChat;
            bool showFauxKeyboardGrid = mainPageVm.ShowFauxKeyboardGrid;
            bool isKeyboardOpen = currentActiveVm != null ? currentActiveVm.IsInputTextFocused : false;

            var newOrientation = ApplicationView.GetForCurrentView().Orientation;
            if (newOrientation != mainPageVm.DeviceOrientation)
            {
                _isRotating = true;
                mainPageVm.DeviceOrientation = newOrientation;
                //   this.ChatControlsContentControl.Visibility = Visibility.Collapsed;
                this.EmoticonPopup.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.ContactList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.ContactList.Opacity = 0;
                this.ChatControlsContentControl.Opacity = 0;
                this.EmoticonPopup.Opacity = 0;
            }


            VisibleBoundsWidth = sender.VisibleBounds.Width;
            VisibleBoundsHeight = sender.VisibleBounds.Height;

            if (newOrientation == ApplicationViewOrientation.Portrait)
            {
                VisibleBoundsHeight += 30;
                this.TabsPopup.Margin = new Thickness(0, -30, 0, 0);
                this.MainPageConnectPopup.Margin = new Thickness(0, -30, 0, 0);
            }
            else if (newOrientation == ApplicationViewOrientation.Landscape)
            {
                this.TabsPopup.Margin = new Thickness(0, 0, 0, 30);
                this.MainPageConnectPopup.Margin = new Thickness(0, 0, 0, 30);
            }
            await Task.Delay(200);
            //if (!isKeyboardOpen && currentActiveVm != null)
            //    currentActiveVm.IsInputTextFocused = false;
            //  this.ChatControlsContentControl.Visibility = Visibility.Visible;

            //  await Task.Delay(100);
            this.EmoticonPopup.Visibility = Visibility.Visible;
            await Task.Delay(150);
            this.ContactList.Visibility = Visibility.Visible;

            mainPageVm.EmoticonControlWidth = sender.VisibleBounds.Width;
            if (_keyboardHeights.ContainsKey(sender.Orientation))
                mainPageVm.EmoticonControlHeight = mainPageVm.FauxKeyboardHeight = _keyboardHeights[sender.Orientation];

            if (newOrientation == ApplicationViewOrientation.Landscape)
                mainPageVm.EmoticonControlHeight += _landscapeYTransformDistance;

            if (mainPageVm.ShowEmoticonPopup)
            {
                mainPageVm.ShowEmoticonPopup = false;
                mainPageVm.ShowEmoticonPopup = true;
            }
            else if (showFauxKeyboardGrid)
            {
                mainPageVm.ShowFauxKeyboardGrid = false;
                mainPageVm.ShowFauxKeyboardGrid = true;
            }
            if (currentActiveVm != null)
            {
                if (isKeyboardOpen)
                    currentActiveVm.IsInputTextFocused = true;
            }
            if (_isRotating)
            {
                this.ContactList.Animate(0, 1, "Opacity", 200, 0);
                this.ChatControlsContentControl.Animate(0, 1, "Opacity", 200, 0);
                this.EmoticonPopup.Animate(0, 1, "Opacity", 200, 0);
            }
            _isRotating = false;
        }


        private void RemoveFakeKeyboardAnimation()
        {
            this.LayoutRoot.Animate(((CompositeTransform)this.LayoutRoot.RenderTransform).TranslateY, 0, "(Grid.RenderTransform).(CompositeTransform.TranslateY)", 300, 0);
        }


        private void ShowFakeKeyboardAnimation(bool animate)
        {
            ViewModelMainPage mainPageVm = this.DataContext as ViewModelMainPage;
            if (mainPageVm.DeviceOrientation == ApplicationViewOrientation.Landscape && !mainPageVm.ShowEmoticonPopup)
            {
                if (this.LayoutRoot.RenderTransform is CompositeTransform && ((CompositeTransform)this.LayoutRoot.RenderTransform).TranslateY > 0)
                    return;


                int animationLength = 300;
                this.LayoutRoot.Animate(((CompositeTransform)this.LayoutRoot.RenderTransform).TranslateY, -_landscapeYTransformDistance, "(Grid.RenderTransform).(CompositeTransform.TranslateY)", animationLength, 0, null, () =>
                    {
                        //TextBlockGroupNameTop.Opacity = 1;
                    });
            }

        }



        private void FauxKeyboardControl_Shown(object sender, EventArgs e)
        {
            this.JivePivot.IsLocked = true;
            ShowFakeKeyboardAnimation(true);
        }

        private void FauxKeyboardControl_hidden(object sender, EventArgs e)
        {
            this.JivePivot.IsLocked = false;
            RemoveFakeKeyboardAnimation();
        }

        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ViewModelMainPage vmMainPage = (ViewModelMainPage)this.DataContext;

            vmMainPage.EmoticonControlWidth = this.LayoutRoot.ActualWidth;
            int storedEmoticonControlIndex = AppSettings.Instance.LastOpenedEmoticonPageIndex;
            vmMainPage.EmoticonControlPivotIndex = 0;
            await Task.Delay(1000);
            vmMainPage.EmoticonControlPivotIndex = 1;
            await Task.Delay(200);
            vmMainPage.EmoticonControlPivotIndex = 2;
            await Task.Delay(200);
            vmMainPage.EmoticonControlPivotIndex = storedEmoticonControlIndex;

            this.EmoticonPopup.Animate(0, 1, "Opacity", 0, 500);
        }

        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            await SuspensionManager.RestoreAsync();
        }

        private async void JivePivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_firstPivotSwipe)
            {
                Pivot pivot = (Pivot)sender;
                ViewModelMainPage vm = (ViewModelMainPage)this.DataContext;
                if (pivot.SelectedIndex == 0)
                {
                    _firstPivotSwipe = false;
                    this.AppBarButtonEmoticonList.Icon = new BitmapIcon() { UriSource = vm.EmoticonButtonIconUri };
                    await Task.Delay(10);
                    var oldTabButtonUrl = vm.TabButtonImageUri;
                    vm.TabButtonImageUri = null;
                    await Task.Delay(1);
                    vm.TabButtonImageUri = oldTabButtonUrl;
                }

            }
        }

        private void LoginPopupGrid_Tapped(object sender, TappedRoutedEventArgs e)
        {
            ((ViewModelMainPage)this.DataContext).IsLoginControlVisible = false;
        }
    }
}
